package com.open.capacity.form.controller;

import com.alibaba.fastjson.JSONObject;
import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.form.model.FormDbLink;
import com.open.capacity.form.service.FormDbLinkService;
import com.open.capacity.form.vo.FormDbLinkVo;
import com.open.capacity.utils.encrypt.Md5Utils;
import com.open.capacity.vo.MapVo;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.list.TreeList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 ftquan 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 * 数据库连接管理
 */
@RestController
@Api(tags = "数据库连接模块api")
public class FormDbLinkController {


    @Autowired
    private FormDbLinkService dbLinkService;


    /**
     * 查询数据库连接
     *
     * @param params
     * @return
     */
    @PreAuthorize("hasAuthority('dbLink:get/dbLinks')")
    @ApiOperation(value = "查询数据库连接")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "父级id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "keyword", value = "关键字", dataType = "String")
    })
    @GetMapping("/dbLinks")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result<List<FormDbLink>> findDbLinks(@RequestParam Map<String, Object> params) {
        List<FormDbLink> list = dbLinkService.findDbLinks(params);
        return Result.succeed(list);
    }


    /**
     * 查询数据库连接tree
     *
     * @return
     */
    @PreAuthorize("hasAuthority('dbLink:get/dbLinks')")
    @ApiOperation(value = "查询数据库连接tree")
    @GetMapping("/dbLinks/tree")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result<List<TreeVo>> treeDbLinks() {
        Map<String, Object> params = new HashMap<>();
        List<FormDbLink> dbLinks = dbLinkService.findDbLinks(params);
        List<TreeVo> treeList = new TreeList();
        dbLinks.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getDbName());
            node.setValue(m.getId());
            node.setShowcheck(false);
            node.setCheckstate(0);
            node.setIsexpand(false);
            node.setComplete(false);
            node.setParentId("0");
            node.setHasChildren(false);

            treeList.add(node);
        });

        return Result.succeed(treeList);
    }


    /**
     * 查询数据库连接map
     *
     * @param ver
     * @return
     */
    @PreAuthorize("hasAuthority('dbLink:get/dbLinks')")
    @ApiOperation(value = "查询数据库连接map")
    @GetMapping("/dbLinks/map")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result<MapVo> mapDbLinks(@RequestParam(value = "ver", required = false) String ver) {
        Map<String, FormDbLinkVo> dictMaps = dbLinkService.getMap();
        MapVo<Map<String, FormDbLinkVo>> vo = new MapVo();
        vo.setData(dictMaps);
        vo.setVer(Md5Utils.hash(JSONObject.toJSONString(dictMaps)));
        return Result.succeed(vo);
    }

    /**
     * 测试数据库连接
     *
     * @param dbLink
     * @param keyValue
     * @return
     */
    @PreAuthorize("hasAuthority('dbLink:post/dbLinks/testConnection')")
    @ApiOperation(value = "查询数据库连接list")
    @PostMapping("/dbLinks/testConnection")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result testConnection(@RequestBody FormDbLink dbLink, String keyValue) {
        Map<String, Object> params = new HashMap<>();
        // params.put("parentId", parentId);
        //  params.put("keyword", keyword);
        //  List<FormDbLink> dbLinks = dbLinkService.findDbLinks(params);
        Result.failed("连接失败,连接串信息有误！");
        return Result.succeed("连接成功！");
    }


    /**
     * 数据库连接新增或者更新
     *
     * @param dbLink
     * @return
     */
    @PreAuthorize("hasAnyAuthority('dbLink:post/dbLinks','dbLink:put/dbLinks')")
    @ApiOperation(value = "保存数据库连接")
    @PostMapping("/dbLinks/saveOrUpdate")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result saveOrUpdate(@RequestBody FormDbLink dbLink, String keyValue) {
        return dbLinkService.saveOrUpdate(dbLink, keyValue);
    }


    /**
     * 删除数据库连接
     * delete /dbLinks/1
     *
     * @param id
     */
    @PreAuthorize("hasAuthority('dbLink:delete/dbLinks/{id}')")
    @ApiOperation(value = "删除数据库连接")
    @DeleteMapping("/dbLinks/{id}")
    @LogAnnotation(name = "表单",module = "form-center", recordRequestParam = false)
    public Result delete(@PathVariable(value = "id") String id) {
        try {
            dbLinkService.delete(id);
            return Result.succeed("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("操作失败");
        }
    }

}
